package service

import (
	"dc-news-admin-api/common/global/consts"
	"dc-news-admin-api/common/resp"
	"dc-news-admin-api/common/utils"
	"dc-news-admin-api/dao"
	"dc-news-admin-api/entity"
	"dc-news-admin-api/vo"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"golang.org/x/crypto/bcrypt"
	"net/http"
)

func LoginService(c *gin.Context, req *vo.LoginReq) {
	admin, err := dao.GetAdminByUsername(req.User)
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.ServerErrorCode, "服务器错误"))
		zap.L().Error(err.Error())
		return
	}
	if admin == nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "用户名或密码错误"))
		return
	}
	err = bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(req.Password))
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "用户名或密码错误"))
		return
	}
	token, err := utils.GenerateToken(admin.ID, admin.Role)
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.ServerErrorCode, "服务器错误"))
		zap.L().Error(err.Error())
		return
	}
	c.JSON(http.StatusOK, vo.NewLoginResp(admin, token))
}

func CreateAdminService(c *gin.Context, req *vo.CreateAdminReq) {
	password := utils.CreateRandomString(8)
	hashBytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	hashStr := string(hashBytes)
	err := dao.CreateAdmin(&entity.Admin{
		Username: req.User,
		Password: hashStr,
		Role:     req.Role,
		IsActive: false,
	})
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "创建失败"))
		return
	}
	c.JSON(http.StatusOK, vo.NewPasswordResp(password))
}

func ModifyAdminAuthService(c *gin.Context, id int, req *vo.ModifyAdminAuthReq) {
	err := dao.ModifyAdminRoleById(id, req.Role)
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "操作失败"))
		return
	}
	c.JSON(http.StatusOK, resp.NewOkResp())
}

func ResetPasswordService(c *gin.Context, id int) {
	password := utils.CreateRandomString(8)
	hashBytes, _ := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
	hashStr := string(hashBytes)
	err := dao.UpdateAdminPasswordById(id, hashStr)
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "操作失败"))
		return
	}
	c.JSON(http.StatusOK, vo.NewPasswordResp(password))
}

func DeleteAdminService(c *gin.Context, id int) {
	err := dao.DeleteAdminById(id)
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "操作失败"))
		return
	}
	c.JSON(http.StatusOK, resp.NewOkResp())
}

func GetAdminListService(c *gin.Context) {
	p := utils.NewPagination(c)
	admins, err := dao.GetAdminListByPage(p)
	if err != nil {
		c.JSON(http.StatusOK, resp.NewErrResp(consts.FailCode, "获取失败"))
		return
	}
	c.JSON(http.StatusOK, vo.NewGetAdminListResp(admins, p))
}
